using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.Threading;
using AutoMapper;
using Core;
using IglooCoder.Commons.WcfNhibernate;
using Infrastucture;
using Omu.ValueInjecter;
using WcfService1.DTO;

namespace WcfService1
{
    // NOTE: You can use the "Rename" command on the "Refactor" InventoryAdjustment to change the class name "InventoryAdjustmentServices" in code, svc and config file together.
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    [NHibernateContext]
    public class InventoryAdjustmentServices : IInventoryAdjustmentServices
    {
        private readonly InventoryAdjustmentRepository InventoryAdjustmentRepository;
        private readonly InventoryRepository _InventoryRepository;
        private readonly MutasiStokRepository _MutasiRepository;
        private readonly InventoryWarehouseRepository _iwRepository;
        private AppParamRepository paramRepository;
        private readonly HppRepository _hppRepository;
        private readonly JurnalRepository _jurnalRepository;

        public InventoryAdjustmentServices()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            var session = new WcfSessionStorage();
            InventoryAdjustmentRepository = new InventoryAdjustmentRepository(session);
            _InventoryRepository = new InventoryRepository(session);
            _MutasiRepository = new MutasiStokRepository(session);
            _iwRepository = new InventoryWarehouseRepository(session);
            paramRepository = new AppParamRepository(session);
            _hppRepository = new HppRepository(session);
            _jurnalRepository = new JurnalRepository(session);
        }

        #region IInventoryAdjustmentServices Members

        public List<InventoryAdjustmentDTO> GetList(int page, out long recordCount, string sortProperty = null,
                                                    string sortType = "ASC")
        {
            var InventoryAdjustments = new List<InventoryAdjustment>();
            var Results = new List<InventoryAdjustmentDTO>();

            if (string.IsNullOrEmpty(sortProperty))
            {
                InventoryAdjustments =
                   InventoryAdjustmentRepository.GetDataPaged(page, 30, "TglAdjustment", "DESC").ToList();
            }
            else
            {
                InventoryAdjustments =
                    InventoryAdjustmentRepository.GetDataPaged(page, 30, sortProperty, sortType).ToList();
            }

            recordCount = InventoryAdjustmentRepository.RecordCount;

            Results = (from i in InventoryAdjustments 
                      select new InventoryAdjustmentDTO()
                      {NoAdj = i.NoAdj,TglAdjustment = i.TglAdjustment,Description = i.Description})
                      .ToList();

            //InventoryAdjustments.ForEach(x =>
            //                                 {
            //                                     var InventoryAdjustmentDto = new InventoryAdjustmentDTO();
            //                                     Mapper.Map(x, InventoryAdjustmentDto);
            //                                     //AutoMapper.Mapper.Map(x.ParentInventoryAdjustment, InventoryAdjustmentDto.ParentInventoryAdjustment);
            //                                     Results.Add(InventoryAdjustmentDto);
            //                                 }
                //);

            return Results;
        }

        public bool Save(InventoryAdjustmentDTO InventoryAdjustmentDTO)
        {
            
            bool res;
            bool IsNew = false;
            bool IsNewInventory = false;
            try
            {
                InventoryAdjustment InventoryAdjustment =
                    InventoryAdjustmentRepository.GetDataOne(x => x.NoAdj == InventoryAdjustmentDTO.NoAdj);
                var paramRounded = paramRepository.GetDataOne(x => x.AppParamName == "BatasRound");
                Decimal batasRounded = Decimal.Parse(paramRounded.AppParamValue);

                if (InventoryAdjustment == null)
                {
                    InventoryAdjustment = new InventoryAdjustment();
                    IsNew = true;
                }

                

                InventoryAdjustmentRepository.ExecuteTransactionNative(() =>
                                                                           {
                                                                               if (!IsNew)
                                                                               {
                                                                                   _MutasiRepository.DeleteMutasiStok(InventoryAdjustment.NoAdj);
                                                                                   InventoryAdjustmentRepository.Delete(InventoryAdjustment);
                                                                                   var NewInventoryAdjustment = new InventoryAdjustment();
                                                                                   NewInventoryAdjustment.modified_date = DateTime.Now;
                                                                                   NewInventoryAdjustment.created_date = InventoryAdjustment.created_date;
                                                                                   Mapper.Map(InventoryAdjustmentDTO, NewInventoryAdjustment);

                                                                                   foreach (InventoryAdjustmentDetail InventoryAdjustmentDetail in
                                                                                   NewInventoryAdjustment.InventoryAdjustmentDetails)
                                                                                   {
                                                                                       InventoryAdjustmentDetail.
                                                                                         InventoryAdjustment =
                                                                                         InventoryAdjustment;

                                                                                       Inventory inventory = _InventoryRepository.GetDataOne(
                                                                                               x =>
                                                                                               x.SerialNumber ==
                                                                                               InventoryAdjustmentDetail.
                                                                                                   Inventory.SerialNumber);
                                                                                       if (inventory == null)
                                                                                           throw new Exception(
                                                                                               "Barang tidak ada, tidak dapat melakukan adjustment!");

                                                                                       inventory.UnitPrice = InventoryAdjustmentDetail.Price;
                                                                                       inventory.IsStock = inventory.Item.IsStock;
                                                                                 
                                                                                       var mutasiStok = new MutasiStok();
                                                                                       mutasiStok.ReferenceNumber = InventoryAdjustment.NoAdj;
                                                                                       mutasiStok.SerialNumber = InventoryAdjustmentDetail.Inventory.SerialNumber;
                                                                                       mutasiStok.Type =
                                                                                           InventoryAdjustment.GetType().
                                                                                               Name;
                                                                                       if (InventoryAdjustment.Type.ToLower() ==
                                                                                           "in")
                                                                                       {
                                                                                           if (InventoryAdjustment.TglAdjustment != null)
                                                                                               mutasiStok.TglMutasi = InventoryAdjustment.TglAdjustment.Value.ToDateTime();

                                                                                           MutasiStok mutasiLast =
                                                                                               _MutasiRepository.
                                                                                                   FindLastMutasi(
                                                                                                       mutasiStok.SerialNumber,
                                                                                                       InventoryAdjustmentDetail.Warehouse.KodeWarehouse
                                                                                                       , mutasiStok.TglMutasi
                                                                                                       );
                                                                                           mutasiStok.QtyMasuk = InventoryAdjustmentDetail.QtyUnit;
                                                                                           mutasiStok.QtySisa = mutasiLast.QtySisa + mutasiStok.QtyMasuk;
                                                                                           mutasiStok.SheetMasuk = InventoryAdjustmentDetail.Tinggi;
                                                                                           mutasiStok.SheetSisa = mutasiLast.SheetSisa + mutasiStok.SheetMasuk;
                                                                                        
                                                                                           mutasiStok.KodeWarehouse =
                                                                                               InventoryAdjustmentDetail.
                                                                                                   Warehouse.KodeWarehouse;
                                                                                       }
                                                                                       else
                                                                                       {
                                                                                           if (InventoryAdjustment.TglAdjustment != null)
                                                                                               mutasiStok.TglMutasi = InventoryAdjustment.TglAdjustment.Value.ToDateTimeSellAdj();

                                                                                           MutasiStok mutasiLast =
                                                                                               _MutasiRepository.
                                                                                                   FindLastMutasi(
                                                                                                   mutasiStok.SerialNumber,
                                                                                                   InventoryAdjustmentDetail.Warehouse.KodeWarehouse
                                                                                                   , mutasiStok.TglMutasi
                                                                                                   );

                                                                                           if (InventoryAdjustmentDetail.Inventory.Item.IsRounded)
                                                                                               mutasiLast.QtySisa = Math.Round(
                                                                                                   mutasiLast.QtySisa, 2, MidpointRounding.AwayFromZero);

                                                                                           mutasiStok.QtyKeluar = InventoryAdjustmentDetail.QtyUnit ;
                                                                                           mutasiStok.SheetKeluar = InventoryAdjustmentDetail.Tinggi;
                                                                                           mutasiStok.QtySisa = mutasiLast.QtySisa - mutasiStok.QtyKeluar;
                                                                                           mutasiStok.SheetSisa = mutasiLast.SheetSisa - mutasiStok.SheetKeluar;
                                                                                           mutasiStok.KodeWarehouse = InventoryAdjustmentDetail.Warehouse.KodeWarehouse;
                                                                                           if (mutasiStok.QtySisa < 0)
                                                                                               throw new Exception(
                                                                                                   mutasiStok.SerialNumber + " Stok tidak mencukupi!");
                                                                                           if (InventoryAdjustmentDetail.Inventory.Item.IsRounded)
                                                                                               if (mutasiStok.QtySisa < batasRounded)
                                                                                                   mutasiStok.QtySisa = 0;
                                                                                       }

                                                                                       _MutasiRepository.SaveOrUpdate(
                                                                                           mutasiStok,inventory.KodePallet);

                                                                                       if (IsNewInventory)
                                                                                           _InventoryRepository.SaveOrUpdate
                                                                                               (inventory);
                                                                                   }

                                                                                   InventoryAdjustmentRepository.Session.SaveOrUpdateCopy(NewInventoryAdjustment);

                                                                               }else
                                                                               {
                                                                                   Mapper.Map(InventoryAdjustmentDTO, InventoryAdjustment);
                                                                                   InventoryAdjustment.NoAdj = GetLastNoAdjustment(InventoryAdjustment);
                                                                                   foreach (InventoryAdjustmentDetail
                                                                                      InventoryAdjustmentDetail in
                                                                                      InventoryAdjustment.InventoryAdjustmentDetails)
                                                                                   {
                                                                                       InventoryAdjustmentDetail.
                                                                                           InventoryAdjustmentDetailId =
                                                                                           0;

                                                                                       InventoryAdjustmentDetail.
                                                                                           InventoryAdjustment =
                                                                                           InventoryAdjustment;

                                                                                       Inventory inventory = _InventoryRepository.GetDataOne(
                                                                                               x =>
                                                                                               x.SerialNumber ==
                                                                                               InventoryAdjustmentDetail.
                                                                                                   Inventory.SerialNumber);
                                                                                       if (inventory == null)
                                                                                           throw new Exception(
                                                                                               "Barang tidak ada, tidak dapat melakukan adjustment!");

                                                                                       inventory.UnitPrice = InventoryAdjustmentDetail.Price;
                                                                                       inventory.IsStock = inventory.Item.IsStock;

                                                                                       var mutasiStok = new MutasiStok();
                                                                                       mutasiStok.ReferenceNumber =
                                                                                           InventoryAdjustment.NoAdj;
                                                                                       mutasiStok.SerialNumber =
                                                                                           InventoryAdjustmentDetail.
                                                                                               Inventory.SerialNumber;
                                                                                       mutasiStok.Type =
                                                                                           InventoryAdjustment.GetType().
                                                                                               Name;
                                                                                       if (InventoryAdjustment.Type.ToLower() ==
                                                                                           "in")
                                                                                       {
                                                                                           if (InventoryAdjustment.
                                                                                              TglAdjustment != null)
                                                                                               mutasiStok.TglMutasi = InventoryAdjustment.TglAdjustment.Value.ToDateTime();

                                                                                           MutasiStok mutasiLast =
                                                                                                _MutasiRepository.
                                                                                                    FindLastMutasi(
                                                                                                        mutasiStok.SerialNumber,
                                                                                                        InventoryAdjustmentDetail.Warehouse.KodeWarehouse
                                                                                                        ,mutasiStok.TglMutasi
                                                                                                        );
                                                                                           mutasiStok.QtyMasuk = InventoryAdjustmentDetail.QtyUnit;
                                                                                           mutasiStok.QtySisa = mutasiLast.QtySisa + mutasiStok.QtyMasuk;
                                                                                           mutasiStok.SheetMasuk = InventoryAdjustmentDetail.Tinggi;
                                                                                           mutasiStok.SheetSisa = mutasiLast.SheetSisa + mutasiStok.SheetMasuk;
                                                                                           //mutasiStok.PanjangMasuk = InventoryAdjustmentDetail.Panjang - mutasiLast.PanjangSisa;
                                                                                           //mutasiStok.LebarMasuk = InventoryAdjustmentDetail.Lebar - mutasiLast.LebarSisa;
                                                                                           //mutasiStok.PanjangSisa = mutasiLast.PanjangSisa + mutasiStok.PanjangMasuk;
                                                                                           //mutasiStok.LebarSisa = mutasiLast.LebarSisa + mutasiStok.LebarMasuk;
                                                                                           mutasiStok.KodeWarehouse =
                                                                                               InventoryAdjustmentDetail.
                                                                                                   Warehouse.KodeWarehouse;
                                                                                       }
                                                                                       else
                                                                                       {
                                                                                           if (InventoryAdjustment.
                                                                                              TglAdjustment != null)
                                                                                               mutasiStok.TglMutasi = InventoryAdjustment.TglAdjustment.Value.ToDateTimeSellAdj();

                                                                                           MutasiStok mutasiLast =
                                                                                               _MutasiRepository.
                                                                                                   FindLastMutasi(
                                                                                                   mutasiStok.SerialNumber,
                                                                                                       InventoryAdjustmentDetail.Warehouse.KodeWarehouse
                                                                                                       ,mutasiStok.TglMutasi
                                                                                                       );
                                                                                           mutasiStok.QtyKeluar = InventoryAdjustmentDetail.QtyUnit;
                                                                                           mutasiStok.SheetKeluar = InventoryAdjustmentDetail.Tinggi;
                                                                                           mutasiStok.QtySisa = mutasiLast.QtySisa - mutasiStok.QtyKeluar;
                                                                                           mutasiStok.SheetSisa = mutasiLast.SheetSisa - mutasiStok.SheetKeluar;
                                                                                           //mutasiStok.PanjangKeluar = mutasiLast.PanjangSisa - InventoryAdjustmentDetail.Panjang;
                                                                                           //mutasiStok.LebarKeluar = mutasiLast.LebarSisa - InventoryAdjustmentDetail.Lebar;
                                                                                           //mutasiStok.PanjangSisa = mutasiLast.PanjangSisa - mutasiStok.PanjangKeluar;
                                                                                           //mutasiStok.LebarSisa = mutasiLast.LebarSisa - mutasiStok.LebarKeluar;
                                                                                           mutasiStok.KodeWarehouse = InventoryAdjustmentDetail.Warehouse.KodeWarehouse;
                                                                                           if (mutasiStok.QtySisa < 0)
                                                                                               throw new Exception(
                                                                                                  mutasiStok.SerialNumber + " Stok tidak mencukupi!");
                                                                                           if (InventoryAdjustmentDetail.Inventory.Item.IsRounded)
                                                                                               if (mutasiStok.QtySisa < batasRounded)
                                                                                                        mutasiStok.QtySisa = 0;
                                                                                       }

                                                                                       _MutasiRepository.SaveOrUpdate(
                                                                                           mutasiStok,inventory.KodePallet);
                                                                                       if (IsNewInventory)
                                                                                           _InventoryRepository.SaveOrUpdate
                                                                                               (inventory);
                                                                                   }
                                                                                   InventoryAdjustmentRepository.SaveOrUpdate(InventoryAdjustment);
                                                                               }
                                                                              
                                                                           });
                res = true;
            }
            catch (Exception ex)
            {
                res = false;
                throw ex;
            }

            return res;
        }


        public bool Delete(InventoryAdjustmentDTO InventoryAdjustmentDto)
        {
            bool res;
            try
            {
                InventoryAdjustment InventoryAdjustment =
                    InventoryAdjustmentRepository.GetDataOne(x => x.NoAdj == InventoryAdjustmentDto.NoAdj);
                InventoryAdjustmentRepository.ExecuteTransactionNative(
                    () =>
                        {
                            if (InventoryAdjustment.Type.ToLower() == "in")
                                foreach (
                                    InventoryAdjustmentDetail InventoryAdjustmentDetail in
                                        InventoryAdjustment.InventoryAdjustmentDetails)
                                {
                                    //Inventory inventory =
                                    //    _InventoryRepository.GetDataOne(
                                    //        x => x.SerialNumber == InventoryAdjustmentDetail.Inventory.SerialNumber);
                                    //_InventoryRepository.Delete(inventory);
                                }
                            _MutasiRepository.DeleteMutasiStok(InventoryAdjustment.NoAdj);
                            InventoryAdjustmentRepository.Delete(InventoryAdjustment);
                        }
                    );

                res = true;
            }
            catch (Exception)
            {
                res = false;
            }

            return res;
        }


        public List<InventoryAdjustmentDTO> GetListByCriteria(Dictionary<String, Object> criteria, string expression,
                                                              int page, out long recordCount)
        {
            var InventoryAdjustments = new List<InventoryAdjustment>();
            var Results = new List<InventoryAdjustmentDTO>();
            InventoryAdjustments = InventoryAdjustmentRepository.GetDataPaged(criteria, expression, page, 30).ToList();
            recordCount = InventoryAdjustmentRepository.RecordCount;
            InventoryAdjustments.ForEach(x =>
                                             {
                                                 var InventoryAdjustmentDto = new InventoryAdjustmentDTO();
                                                 Mapper.Map(x, InventoryAdjustmentDto);
                                                 Results.Add(InventoryAdjustmentDto);
                                             }
                );

            return Results;
        }


        public List<InventoryAdjustmentDTO> GetAllInventoryAdjustment()
        {
            List<InventoryAdjustment> InventoryAdjustments = InventoryAdjustmentRepository.FetchAll().ToList();
            var Results = new List<InventoryAdjustmentDTO>();
            InventoryAdjustments.ForEach(x =>
                                             {
                                                 var InventoryAdjustmentDto = new InventoryAdjustmentDTO();
                                                 Mapper.Map(x, InventoryAdjustmentDto);
                                                 Results.Add(InventoryAdjustmentDto);
                                             }
                );

            return Results;
        }


        public InventoryAdjustmentDTO GetInventoryAdjustment(String kodeInventoryAdjustment)
        {
            InventoryAdjustment InventoryAdjustment =
                InventoryAdjustmentRepository.GetDataOne(x => x.NoAdj == kodeInventoryAdjustment);
            var InventoryAdjustmentDto = new InventoryAdjustmentDTO();
            Mapper.Map(InventoryAdjustment, InventoryAdjustmentDto);
            return InventoryAdjustmentDto;
        }

        public List<InventoryAdjustmentDTO> GetInventoryAdjustmentList(string kodeInventoryAdjustment)
        {
            List<InventoryAdjustment> InventoryAdjustments =
                InventoryAdjustmentRepository.GetDataList(x => x.NoAdj.Contains(kodeInventoryAdjustment)).ToList();
            var Results = new List<InventoryAdjustmentDTO>();
            InventoryAdjustments.ForEach(x =>
                                             {
                                                 var InventoryAdjustmentDto = new InventoryAdjustmentDTO();
                                                 Mapper.Map(x, InventoryAdjustmentDto);
                                                 Results.Add(InventoryAdjustmentDto);
                                             }
                );

            return Results;
        }


        public bool DeleteDetail(InventoryAdjustmentDetailDTO InventoryAdjustmentDetailDTO)
        {
            bool res;
            try
            {
                var InventoryAdjustmentDetail =
                    InventoryAdjustmentRepository.Session.Get<InventoryAdjustmentDetail>(
                        InventoryAdjustmentDetailDTO.InventoryAdjustmentDetailId);
                InventoryAdjustmentRepository.ExecuteTransactionNative(
                    () =>
                        {
                            //var inventory = _InventoryRepository.GetDataOne(x => x.SerialNumber == InventoryAdjustmentDetail.Inventory.SerialNumber);
                            //_InventoryRepository.Delete(inventory);
                            _MutasiRepository.DeleteMutasiStok(InventoryAdjustmentDetailDTO.NoAdj,
                                                               InventoryAdjustmentDetailDTO.Inventory.SerialNumber);
                            InventoryAdjustmentRepository.DeleteDetail(InventoryAdjustmentDetail,
                                                                       InventoryAdjustmentDetailDTO.
                                                                           InventoryAdjustmentDetailId);
                        }
                    );
                res = true;
            }
            catch (Exception)
            {
                res = false;
            }

            return res;
        }

        public string GetLastNoAdjustment(InventoryAdjustment inventoryAdjustment)
        {
            var appParamServices = new AppParamServices();
            AppParamDTO param = appParamServices.GetAppParamList("KodeAdj").FirstOrDefault();
            var kodeDepan = param.AppParamValue;
            kodeDepan = inventoryAdjustment.Type == "in" ? kodeDepan + "-IN" : kodeDepan + "-OUT";
            string res = InventoryAdjustmentRepository.GetMaxNumber(kodeDepan);
            if (string.IsNullOrEmpty(res))
                res = param.AppParamValue;

            string formatSO = "0000";
            string lastNo = string.Empty;
            string kodeSO;
            if (res.Length <= 4)
            {
                lastNo = formatSO;
                kodeSO = res;
            }
            else
            {
                lastNo = res.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[2];
                kodeSO = res.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[0];
            }
            string soNum = formatSO.Substring(0, formatSO.Length - (int.Parse(lastNo) + 1).ToString().Length) +
                           (int.Parse(lastNo) + 1);

            return kodeSO + "/" + DateTime.Now.Year + "/" + soNum;
                    
        }

        public bool SendEmail(InventoryAdjustmentDTO obj, String DestinationFolder)
        {
            var mailServices = new MailServices();
            InventoryAdjustment Obj = InventoryAdjustmentRepository.GetDataOne(x => x.NoAdj == obj.NoAdj);
            obj = Mapper.Map(Obj, obj);
            return mailServices.SendEmail(obj,DestinationFolder);
        }

        public void UpdateStatus(InventoryAdjustmentDTO inventoryAdjustmentDto, Status status)
        {
            InventoryAdjustmentRepository.UpdateStatus(inventoryAdjustmentDto.NoAdj, (int)status);
        }

        public void CreateJurnal(InventoryAdjustment adjustment)
        {
            //Piutang
            Jurnal jurnal = new Jurnal();
            jurnal.NoVoucher = adjustment.NoAdj;
            jurnal.TglJurnal = adjustment.TglAdjustment.Value;
            jurnal.Description = adjustment.Description;
            jurnal.ReffNumber = adjustment.NoAdj;
            jurnal.TipeJurnal = typeof(InventoryAdjustment).ToString();

            foreach (var detail in adjustment.InventoryAdjustmentDetails)
            {
                if (adjustment.Type.ToLower() == "in")
                {
                    var hppServices = new HppServices();
                    hppServices.CreateHpp(adjustment);
                    //Kredit Hpp
                    var inventory = _InventoryRepository.GetDataOne(x => x.SerialNumber == detail.Inventory.SerialNumber);
                    var hpp = _hppRepository.FindLastHpp(inventory.SerialNumber, adjustment.TglAdjustment.Value);
                    if (hpp.QtyAkhir == 0)throw new Exception("Hpp sebelumnya tidak ada!");
                    jurnal.JurnalDetails.Add(new JurnalDetail() { AccountNumber = inventory.Item.CoaHpp, Kredit = hpp.HppAkhir * detail.QtyUnit, Jurnal = jurnal, Description = inventory.Item.ItemId + ":" + inventory.Item.CoaHpp });
                    //Debit Inventory
                    jurnal.JurnalDetails.Add(new JurnalDetail() { AccountNumber = inventory.Item.CoaInventory, Debit = hpp.HppAkhir * detail.QtyUnit, Jurnal = jurnal, Description = inventory.Item.ItemId + ":" + inventory.Item.CoaInventory });    
                }else
                {
                    //Hpp Debit 
                    var inventory = _InventoryRepository.GetDataOne(x => x.SerialNumber == detail.Inventory.SerialNumber);
                    var hpp = _hppRepository.FindLastHpp(inventory.SerialNumber, adjustment.TglAdjustment.Value);
                    if (hpp.QtyAkhir == 0) throw new Exception("Hpp sebelumnya tidak ada!");
                    jurnal.JurnalDetails.Add(new JurnalDetail() { AccountNumber = inventory.Item.CoaHpp, Debit = hpp.HppAkhir * detail.QtyUnit, Jurnal = jurnal, Description = inventory.Item.ItemId + ":" + inventory.Item.CoaHpp });
                    //Inventory Kredit
                    jurnal.JurnalDetails.Add(new JurnalDetail() { AccountNumber = inventory.Item.CoaInventory, Kredit = hpp.HppAkhir * detail.QtyUnit, Jurnal = jurnal, Description = inventory.Item.ItemId + ":" + inventory.Item.CoaInventory });

                    var hppServices = new HppServices();
                    hppServices.CreateHpp(adjustment);
                }
                
            }

            List<JurnalDetail> results = new List<JurnalDetail>();
            foreach (var gjd in jurnal.JurnalDetails.GroupBy(x => x.Description))
            {
                results.Add(new JurnalDetail()
                {
                    AccountNumber = jurnal.JurnalDetails.FirstOrDefault(x => x.Description == gjd.Key).AccountNumber,
                    Debit = jurnal.JurnalDetails.Where(x => x.Description == gjd.Key).Sum(x => x.Debit),
                    Kredit = jurnal.JurnalDetails.Where(x => x.Description == gjd.Key).Sum(x => x.Kredit),
                    Description = jurnal.JurnalDetails.FirstOrDefault(x => x.Description == gjd.Key).Description,
                    Jurnal = jurnal
                });
            }

            jurnal.JurnalDetails = results;
            _jurnalRepository.SaveOrUpdate(jurnal);

          
        }


        public void Posting(IEnumerable<InventoryAdjustmentDTO> InventoryAdjustmentDtos)
        {
            InventoryAdjustmentRepository.ExecuteTransactionNative(() =>
            {
                foreach (var InventoryAdjustmentDto in InventoryAdjustmentDtos)
                {
                    var si = InventoryAdjustmentRepository.GetDataOne(x => x.NoAdj == InventoryAdjustmentDto.NoAdj);
                    InventoryAdjustmentRepository.UpdateStatus(InventoryAdjustmentDto.NoAdj, 3);
                    CreateJurnal(si);
                }
            });

        }


        public void UnPosting(IEnumerable<InventoryAdjustmentDTO> InventoryAdjustmentDtos)
        {
            InventoryAdjustmentRepository.ExecuteTransactionNative(() =>
            {
                foreach (var InventoryAdjustmentDto in InventoryAdjustmentDtos)
                {
                    var InventoryAdjustment = InventoryAdjustmentRepository.GetDataOne(x => x.NoAdj == InventoryAdjustmentDto.NoAdj);
                    InventoryAdjustmentRepository.UpdateStatus(InventoryAdjustment.NoAdj, 1);
                    _jurnalRepository.Delete(new Jurnal() { NoVoucher = InventoryAdjustmentDto.NoAdj });
                    _hppRepository.DeleteHpp(InventoryAdjustment.NoAdj);
                }
            });

        }


        public IEnumerable<InventoryAdjustmentDTO> GetListByPeriode(DateTime tglstart, DateTime tglend)
        {
            List<InventoryAdjustment> adjustments = InventoryAdjustmentRepository.GetDataList(x => x.TglAdjustment >= tglstart && x.TglAdjustment <= tglend).ToList();
            var results = new List<InventoryAdjustmentDTO>();

            foreach (var adjustment in adjustments)
            {
                var adjustmentDTO = new InventoryAdjustmentDTO();
                adjustmentDTO.InjectFrom(adjustment);
                results.Add(adjustmentDTO);
            }

            return results;
        }

        #endregion
    }
}